package dosgi.distribution;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;

import dosgi.distribution.remote.RemoteInvocationClient;
import dosgi.distribution.remote.RemoteInvocationServer;
import dosgi.distribution.remote.impl.RemoteInvocationClientImpl;
import dosgi.distribution.remote.impl.RemoteInvocationServerImpl;

public class Activator implements BundleActivator {

	public static BundleContext context;
	
	private RemoteInvocationClient client;
	private RemoteInvocationServer server;
	private Thread serverThread;
	private ServiceRegistration<?> serviceRegistration;
	public static String QUEUE_NAME;
	static {
		try {
			QUEUE_NAME = Activator.generateQueueName();
		} catch (UnknownHostException e) {
			//Just ignore that exception cuz its not gonna happen
		}
		
	}
	
	static BundleContext getContext() {
		return context;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext bundleContext) throws Exception {
		context = bundleContext;
		
		server = new RemoteInvocationServerImpl();
		serverThread = new Thread(server);
		
		serverThread.start();
		
		client = new RemoteInvocationClientImpl();
		
		serviceRegistration = context.registerService(RemoteInvocationClient.class.getName(), client, null);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext bundleContext) throws Exception {
		client.close();
		serverThread.join();
		server.close();
		
		Activator.context = null;
		serviceRegistration.unregister();
	}

	
	private static String generateQueueName() throws UnknownHostException {
		//generujemy nazwe kolejki i wrzucamy do propertiesow
		//latwiejsza droga
		String ip = InetAddress.getLocalHost().getHostAddress();
		String queueName;
		if (System.getProperty("osgi-" + FrameworkUtil.class.hashCode()) != null) {
			queueName = System.getProperty("osgi-" + FrameworkUtil.class.hashCode());
		} else {
			queueName = ip + "@" + UUID.randomUUID().toString();
		}
		return queueName;
	}
}
